package com.sky.gateway.filter;

import com.sky.common.config.AuthProperties;
import com.sky.common.config.JwtProperties;
import com.sky.common.constant.JwtClaimsConstant;
import com.sky.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * ClassName: com.sky.gateway.filter
 * Datetime: 2024/9/30 下午6:03
 * Description:
 *
 * @author 汪佳泉
 * @version 1.0
 * @since 1.0
 */


@Component
@RequiredArgsConstructor
@EnableConfigurationProperties({JwtProperties.class, AuthProperties.class})
public class AuthGlobalFilter implements GlobalFilter {

    private final JwtUtil jwtUtil;

    private final AuthProperties authProperties;

    private final JwtProperties jwtProperties;

    // uri匹配工具
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 响应式编程 API和传统的Servlet编程略有不同
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request对象
        ServerHttpRequest request = exchange.getRequest();
        // 判断是否需要拦截
        if(isExclude(request.getPath().toString())){
            // 不需要拦截的话直接放行
            return chain.filter(exchange);
        }
        // 获取请求头中的token
        List<String> list = request.getHeaders().get(jwtProperties.getAdminTokenName());
        String token = null;
        if(!Collections.isEmpty(list)){
            token = list.get(0);
        }
        // 对token进行解密
        Long empId = null;
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
        } catch (Exception e){
            // 无效进行拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        // 传递用户信息
        String userID = empId.toString();
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder ->
                        builder.header("user-info", userID))
                .build();
        // 6.放行
        return chain.filter(newExchange);
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }


}
